<?php

if (!defined('BASEPATH')) exit('No direct script access allowed');
	
 /**
 * Dayrui Website Management System
 *
 * @since		version 2.6.0
 * @author		Dayrui <dayrui@gmail.com>
 * @license     http://www.dayrui.com/license
 * @copyright   Copyright (c) 2011 - 9999, Dayrui.Com, Inc.
 */
 
class Api extends M_Controller {

    /**
     * 构造函数
     */
    public function __construct() {
        parent::__construct();
    }

    /**
     * 会员登录信息JS调用
     */
    public function member() {
        ob_start();
        $this->template->display('member.html');
        $html = ob_get_contents();
        ob_clean();
		$format = $this->input->get('format');
		// 页面输出
		if ($format == 'jsonp') {
			$data = $this->callback_json(array('html' => $html));
			echo $this->input->get('callback').'('.$data.')';
		} elseif ($format == 'json') {
			echo $this->callback_json(array('html' => $html));
		} else {
			echo 'document.write("'.addslashes(str_replace(array("\r", "\n", "\t", chr(13)), array('', '', '', ''), $html)).'");';
		}
        exit;
    }

    public function check() {
	    if($this->member['uid'] < 1) {
		    exit(dr_json(0));
	    } else {
		    exit(dr_json(1));
	    }
    }


    /**
     * 广告访问
     */
    public function poster_show() {

        $id = (int)$this->input->get('id');
        $data = $this->site[SITE_ID]->where('id', $id)->get(SITE_ID.'_poster')->row_array();
        if ($data) {
            $value = dr_string2array($data['value']);
            if ($value['url']) {
                $this->site[SITE_ID]->where('id', $id)->update(SITE_ID.'_poster', array(
                    'clicks' => $data['clicks'] + 1
                ));
                redirect($value['url'], 'refresh');
            } else {
                $this->msg('此广告没有链接地址');
            }
        } else {
            $this->msg('广告信息不存在或者已过期');
        }

    }
    /**
     * 广告调用
     */
    public function poster() {

        $id = (int)$this->input->get('id');
        $html = dr_poster($id);
        $html = addslashes(str_replace(array("\r", "\n", "\t", chr(13)), array('', '', '', ''), $html));
        echo 'document.write("'.$html.'");';

    }


    /**
     * ck播放器接口
     */
    public function ckplayer() {

        $at = $this->input->get('at');
        $form = $this->input->get('form');
        $data = array(
            'text' => '',
            'api_url' => SITE_URL.'index.php?c=api&m=ckplayer',
            'server_url' => SITE_URL.'dayrui/ckplayer/',
        );

        // 功能部分
        switch($at) {
            case 'js' : // 动态加载js
                //
                $text = $this->get_cache('poster-text-'.SITE_ID);
                if ($text) {
                    // 文字滚动广告
                    $this->load->model('poster_model');
                    $poster = $this->poster_model->poster($text);
                    if ($poster) {
                        $url = $this->poster_model->get_url($poster['id']);
                        $value = dr_string2array($poster['value']);
                        if ($value) {
                            $data['text'] = '{a href="'.$url.'" target="_blank"}{font color="'.$value['color'].'" size="12"}'.($value['text'] ? dr_clearhtml($value['text']) : '没有输入广告内容').'{/font}{/a}';
                        }
                    }
                }
                $code = file_get_contents(FCPATH.'dayrui/ckplayer/config/config.js');
                break;
            case 'share' : // 分享
                header('Content-Type: text/xml');
                $code = file_get_contents(FCPATH.'dayrui/ckplayer/config/share.xml');
                break;
        }

        // 兼容php5.5
        if (version_compare(PHP_VERSION, '5.5.0') >= 0) {
            $rep = new php5replace($data);
            $code = preg_replace_callback('#{([a-z_0-9]+)}#U', array($rep, 'php55_replace_data'), $code);
            unset($rep);
        } else {
            extract($data);
            $code = preg_replace('#{([a-z_0-9]+)}#Ue', "\$\\1", $code);
        }

        exit($code);

    }

    /**
     * 会员登录信息JS调用
     */
    public function userinfo() {
        ob_start();
        $this->template->display('api.html');
        $html = ob_get_contents();
        ob_clean();
        $html = addslashes(str_replace(array("\r", "\n", "\t", chr(13)), array('', '', '', ''), $html));
        echo 'document.write("'.$html.'");';
    }

    /**
     * 自定义信息JS调用
     */
    public function template() {
        $this->api_template();
    }

    /**
	 * 更新浏览数
	 */
	public function hits() {
	
	    $id = (int)$this->input->get('id');
	    $dir = $this->input->get('module', TRUE);
		$name = 'hits'.$dir.SITE_ID.$id;
		$hits = (int)$this->get_cache_data($name);
        if (!is_file(FCPATH.'cache/data/module-'.SITE_ID.'-'.$dir.'.cache.php')) {
            exit;
        }
		
		if (!$hits) {
			$data = $this->site[SITE_ID]->where('id', $id)->select('hits')->get($this->db->dbprefix(SITE_ID.'_'.$dir))->row_array();
			$hits = (int)$data['hits'];
		}
		
		$hits++;
		$this->set_cache_data($name, $hits, (int)SYS_CACHE_MSHOW);
		
		$this->site[SITE_ID]->where('id', $id)->update($this->db->dbprefix(SITE_ID.'_'.$dir), array('hits' => $hits));

		exit("document.write('$hits');");
	}

    /**
	 * 更新扩展的浏览数
	 */
	public function ehits() {

	    $id = (int)$this->input->get('id');
	    $dir = $this->input->get('module', TRUE);
		$name = 'ehits'.$dir.SITE_ID.$id;
		$hits = (int)$this->get_cache_data($name);
        if (!is_file(FCPATH.'cache/data/module-'.SITE_ID.'-'.$dir.'.cache.php')) {
            exit;
        }

		if (!$hits) {
			$data = $this->site[SITE_ID]->where('id', $id)->select('hits')->get(SITE_ID.'_'.$dir.'_extend')->row_array();
			$hits = (int)$data['hits'];
		}

		$hits++;
		$this->set_cache_data($name, $hits, (int)SYS_CACHE_MSHOW);

		$this->site[SITE_ID]->where('id', $id)->update(SITE_ID.'_'.$dir.'_extend', array('hits' => $hits));

		exit("document.write('$hits');");
	}
	
	/**
	 * 发送桌面快捷方式
	 */
	public function desktop() {
		
		$site = (int)$this->input->get('site');
		$module = $this->input->get('module');
		
		if ($site && !$module) {
			$url = $this->SITE[$site]['SITE_URL'];
			$name = $this->SITE[$site]['SITE_NAME'].'.url';
		} elseif ($site && $module) {
			$mod = $this->get_cache('module-'.$site.'-'.$module);
			$url = $mod['url'];
			$name = $mod['name'].'.url';
		}  else {
			$url = $this->SITE[SITE_ID]['SITE_URL'];
			$name = $this->SITE[SITE_ID]['SITE_NAME'].'.url';
		}
		
		$data = "
		[InternetShortcut]
		URL={$url}
		IconFile={$url}favicon.ico
		Prop3=19,2
		IconIndex=1
		";
		$mime = 'application/octet-stream';
		
		header('Content-Type: "' . $mime . '"');
		header('Content-Disposition: attachment; filename="' . $name . '"');
		header("Content-Transfer-Encoding: binary");
		header('Expires: 0');
		header('Pragma: no-cache');
		header("Content-Length: " . strlen($data));
		echo $data;
	}
	
	/**
	 * 伪静态测试
	 */
	public function test() {
		header('Content-Type: text/html; charset=utf-8');
		echo '服务器支持伪静态';
	}
	
	/**
	 * 自定义数据调用（老版本）
	 */
	public function data() {
		exit('此方法已失效，请使用m=data2');
	}
	
	/**
	 * 自定义数据调用（新版本）
	 */
	public function data2() {

		// 认证码
		$auth = $this->input->get('auth');
		if ($auth != md5(SYS_KEY)) {
			// 授权认证码不正确
			$data = array('msg' => '授权认证码不正确', 'code' => 0);
		} else {
			// 解析数据
            $param = $this->input->get('param');
            if ($param == 'login') {
                // 登录认证
                $code = $this->member_model->login($this->input->get('username'), $this->input->get('password'), 0, 1);
                if (is_array($code)) {
                    $data = array(
						'msg' => 'ok',
						'code' => 1,
						'return' => $this->member_model->get_member($code['uid'])
					);
                } elseif ($code == -1) {
                    $data = array('msg' => lang('m-003'), 'code' => 0);
                } elseif ($code == -2) {
                    $data = array('msg' => lang('m-004'), 'code' => 0);
                } elseif ($code == -3) {
                    $data = array('msg' => lang('m-005'), 'code' => 0);
                } elseif ($code == -4) {
                    $data = array('msg' => lang('m-006'), 'code' => 0);
                }
            } elseif ($param == 'update_avatar') {
                // 更新头像
                $uid = (int)$_REQUEST['uid'];
                $file = $_REQUEST['file'];
                //
                // 创建图片存储文件夹
                $dir = SYS_UPLOAD_PATH.'/member/'.$this->uid.'/';
                if (!file_exists($dir)) {
                    mkdir($dir, 0777, true);
                }
                file_put_contents($dir.'45x45.jpg', $file);
                list($width, $height, $type, $attr) = getimagesize($dir.'45x45.jpg');
                if (!$type) {
                    $data = array(
                        'msg' => '错误的文件格式，请传输图片的字符',
                        'code' => 0
                    );
                } else {
                    $data = array(
                        'code' => 1,
                        'msg' => '更新成功'
                    );
                    // 更新头像
                    $this->db->where('uid', $uid)->update('member', array('avatar' => $uid));
                }
            } elseif ($param == 'upload') {
                // 文件上传接口
                if (!isset($_FILES['file']['name'])) {
                    if (!$_FILES) {
                        $data = array('msg' => '不是正确的文件上传请求，请检查请求参数是否正确', 'code' => 0);
                    } else {
                        $data = array('msg' => 'file值不存在，请检查请求参数是否正确', 'code' => 0);
                    }
                } else {
                    $uid = (int)$this->input->get('uid');
                    $member = $this->member_model->get_base_member($uid);
                    if ($member) {
                        $ext = $this->input->get('ext');
                        if (!$ext) {
                            $data = array('msg' => '文件扩展名不存在', 'code' => 0);
                        } else {
                            // 开始上传处理
                            $dir = SYS_UPLOAD_PATH.'/app/';
                            $path = date('Ym', SYS_TIME);
                            $name = substr(md5('app'.$uid.SYS_TIME.rand(0, 9999)), rand(0, 10), 12);
                            if (!is_dir(FCPATH.$dir.$path.'/')) {
                                mkdir(FCPATH.$dir.$path.'/');
                            }
                            if (!is_dir(FCPATH.$dir.$path.'/')) {
                                $data = array('msg' => '服务器无法创建上传目录：'.FCPATH.$dir.$path.'/', 'code' => 0);
                            } else {
                                $path = $dir.$path.'/'.$name.'.'.$ext;
                                if (!move_uploaded_file($_FILES['file']['tmp_name'], FCPATH.$path)) {
                                    $data = array('msg' => '文件创建失败', 'code' => 0);
                                } else {
                                    // 判断是否是正确的图片
                                    if (in_array($ext, array('jpg', 'jpeg', 'png', 'gif'))) {
                                        $img = getimagesize($path);
                                        if (!$img) {
                                            $data = array('msg' => '上传文件不是一个正确的图片（'.$ext.'）', 'code' => 0);
                                            @unlink($path);
                                        }
                                    }
                                    if (!$data) {
                                        // 入库附件
                                        $this->db->replace('attachment', array(
                                            'uid' => $uid,
                                            'siteid' => 1,
                                            'author' => $member['username'],
                                            'tableid' => 0,
                                            'related' => '',
                                            'fileext' => $ext,
                                            'filemd5' => $file ? md5($file) : 0,
                                            'download' => 0,
                                            'filesize' => strlen($file),
                                        ));
                                        $id = $this->db->insert_id();
                                        // 增加至未使用附件表
                                        $this->db->replace('attachment_unused', array(
                                            'id' => $id,
                                            'uid' => $uid,
                                            'siteid' => 1,
                                            'author' => $member['username'],
                                            'remote' => 0,
                                            'fileext' => $ext,
                                            'filename' => $name,
                                            'filesize' => strlen($file),
                                            'inputtime' => SYS_TIME,
                                            'attachment' => $path,
                                            'attachinfo' => '',
                                        ));
                                        $data = array(
                                            'id' => $id,
                                            'url' => SITE_URL.$path,
                                            'code' => 1,
                                            'msg' => '上传成功',
                                        );
                                    } else {
                                        $data = array('msg' => '入库失败', 'code' => 0);
                                        @unlink($path);
                                    }
                                }
                            }
                        }
                    } else {
                        $data = array('msg' => '会员不存在', 'code' => 0);
                    }
                }
            } elseif ($param == 'function') {
                // 执行函数
                $name = $this->input->get('name', true);
				if (function_exists($name)) {
					$_param = array();
					$_getall = $this->input->get(null, true);
					if ($_getall) {
						for ($i=1; $i<=10; $i++) {
							if (isset($_getall['p'.$i])) {
								$_param[] = $_getall['p'.$i];
							} else {
								break;
							}
						}
					}
                    $data = array('msg' => '', 'code' => 1, 'result' => call_user_func_array($name, $_param));
				} else {
                    $data = array('msg' => '函数 （'.$name.'）不存在', 'code' => 0);
				}
            } elseif ($param == 'get_file') {
                // 获取文件地址
                $info = get_attachment((int)$this->input->get('id'));
                if (!$info) {
                    $data = array('msg' => lang('m-326'), 'code' => 0, 'url' => '');
                } else {
                    $data = array('msg' => '', 'code' => 1, 'url' => dr_get_file($info['attachment']));
                }
            } else {
                // list数据查询
                $data = $this->template->list_tag($param);
                unset($data['sql'], $data['pages']);
            }
		}
		// 接收参数
		$format = $this->input->get('format');
		// 页面输出
		if ($format == 'php') {
			print_r($data);
		} elseif ($format == 'jsonp') {
			// 自定义返回名称
			echo $this->input->get('callback').'('.$this->callback_json($data).')';
		} else {
			// 自定义返回名称
			echo $this->callback_json($data);
		}
		exit;
	}
}
